<template>
  <div class="goods-detail">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'MallGoodsList' }">
        商品列表
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        {{ editMode ? '商品详情' : '新增商品' }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容 -->
    <el-form
      :model="info"
      :rules="mallRule"
      label-width="110px"
      label-position="right"
      ref="mallForm"
    >
      <h2>商品设置</h2>
      <div class="box">
        <el-form-item prop="templateCode" label="商品模板">
          <goods-template v-model="info.templateCode"></goods-template>
        </el-form-item>
        <el-form-item prop="title" label="商品名称">
          <el-input v-model="info.title"></el-input>
        </el-form-item>
        <el-form-item prop="uid" label="发布用户">
          <el-input v-model="info.nickname" disabled></el-input>
          <el-button type="primary" @click="dialogVisible = true">选择用户</el-button>
        </el-form-item>
        <el-form-item prop="categoryId" label="商品分类">
          <el-select v-model="info.categoryId" clearable @change="categoryChange">
            <el-option
              v-for="(item, index) in categoryList"
              :key="index"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="kind" label="商品类型">
          <el-radio-group v-model="info.kind">
            <el-radio :label="0">实物商品</el-radio>
            <el-radio :label="1">虚拟商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="deliverPrice" v-if="!info.kind" label="运费">
          <el-input-number
            v-model="info.deliverPrice"
            :precision="2"
            :step="0.1"
            :min="0"
            placeholder="仅实物商品填写"
          ></el-input-number>
        </el-form-item>
        <el-form-item prop="returnable" label="退换货配置">
          <el-radio-group v-model="info.returnable">
            <el-radio :label="1">支持退换货</el-radio>
            <el-radio :label="0">不可退换货</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="showPrice" label="划线价">
          <el-input v-model="info.showPrice" placeholder="请输入划线价"></el-input>
          <!-- <el-input-number
            v-model="info.showPrice"
            :precision="2"
            :step="0.1"
            :min="0"
            placeholder="请输入划线价"
          ></el-input-number> -->
        </el-form-item>
        <el-form-item prop="deliverUnit" label="单位">
          <el-input v-model="info.deliverUnit" placeholder="比如：份/瓶/张/斤"></el-input>
        </el-form-item>
        <el-form-item prop="period" v-if="info.templateCode === '1'" label="时间">
          <el-date-picker
            v-model="info.period"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="address" label="地点" v-if="info.templateCode === '1'">
          <el-input v-model="info.address"></el-input>
        </el-form-item>
        <el-form-item
          prop="longitude"
          label="经度"
          v-if="info.address && info.templateCode === '1'"
        >
          <el-input v-model="info.longitude"></el-input>
        </el-form-item>
        <el-form-item prop="latitude" label="纬度" v-if="info.address && info.templateCode === '1'">
          <el-input v-model="info.latitude"></el-input>
          <el-button type="primary" @click="searchLongLat">查询经纬度</el-button>
        </el-form-item>
        <el-form-item prop="eticket" label="电子票配置" v-if="info.templateCode === '1'">
          <el-radio-group v-model="info.eticket">
            <el-radio :label="1">有电子票</el-radio>
            <el-radio :label="0">无电子票</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="showIntro" label="门票页相关资料" v-if="info.templateCode === '1'">
          <el-radio-group v-model="info.showIntro">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item prop="price" label="价格">
          <el-input-number
            v-model="info.price"
            :precision="2"
            :step="0.1"
            :min="0"
            placeholder="请填写商品价格"
          ></el-input-number> 
        </el-form-item>-->
        <el-form-item prop="skuImage" label="横划图片" v-if="info.templateCode === '1'">
          <el-row>
            <upload-resource
              is-public
              @upload="(img) => $set(info, 'skuImage', img.url)"
              :folder="'mallImg' + '/' + imgDate"
            ></upload-resource>
          </el-row>
          <el-row v-if="info.skuImage">
            <img style="max-height: 200px;" :src="info.skuImage" alt="" />
          </el-row>
          <el-button @click="$set(info, 'skuImage', '')" type="danger" v-if="info.skuImage">
            删除图片
          </el-button>
        </el-form-item>
        <el-form-item prop="bannerTemplate" label="商品闪图模板">
          <el-radio-group v-model="info.bannerTemplate">
            <el-radio :label="0">单张图</el-radio>
            <el-radio :label="1">多张图</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="imageList"
          class="img-list"
          label="商品图片"
          v-if="info.bannerTemplate === 0 || info.bannerTemplate === 1"
        >
          <el-row v-if="info.bannerTemplate === 0">闪图模式为单张图时，最多上传一张图片</el-row>
          <el-row v-else>第一张图片默认为商品封面图片，可拖动排序（最多上传五张图）</el-row>
          <el-row>
            <upload-resource
              :multiple="info.bannerTemplate === 0 ? false : true"
              is-public
              @upload="uploadImg"
              :folder="'mallImg' + '/' + imgDate"
            ></upload-resource>
          </el-row>
          <el-row>
            <draggable v-model="info.imageList" handle=".drag-btn" @end="dragEnd">
              <div v-for="(item, index) in info.imageList" :key="index" class="img-oper">
                <img :src="item" alt="" />
                <div class="oper">
                  <i class="el-icon-delete" @click="del(index)"></i>
                  <i class="drag-btn el-icon-rank"></i>
                </div>
              </div>
            </draggable>
          </el-row>
        </el-form-item>
        <el-form-item prop="detail" label="移动端商品详情" class="gap">
          <editor v-model="info.detail" style="height: 100%"></editor>
        </el-form-item>
        <el-form-item prop="pcDetail" label="PC端商品详情" class="gap">
          <editor v-model="info.pcDetail" style="height: 100%"></editor>
        </el-form-item>
        <el-form-item prop="instruction" label="移动端商品须知">
          <editor v-model="info.instruction" style="height: 100%"></editor>
        </el-form-item>
        <el-form-item prop="pcInstruction" label="PC端商品须知">
          <editor v-model="info.pcInstruction" style="height: 100%"></editor>
        </el-form-item>
        <el-form-item prop="extra" label="入场须知" v-if="info.templateCode === '1'">
          <editor v-model="info.extra" style="height: 100%"></editor>
        </el-form-item>
      </div>

      <!-- <h2>商品标签</h2>
      <div class="box">
      </div> -->

      <!-- 属性类别: 0-基础属性, 1-销售属性 -->
      <h2>基础属性</h2>
      <div class="box">
        <div v-for="(item, index) in info.attrList" :key="index">
          <el-form-item
            :prop="`attrList.${index}.values`"
            :rules="item.required ? validateBaseOrSeal : []"
            :label="item.title + '：'"
            v-if="item.kind === 0"
          >
            <component
              :is="item.style === 'datetime' ? 'el-date-picker' : 'el-' + item.style"
              v-model="item.values[0]"
              :type="item.style === 'datetime' ? 'datetimerange' : ''"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              @input="inputUpdate"
            ></component>
          </el-form-item>
        </div>
      </div>

      <h2>销售信息</h2>
      <div class="box">
        <h3>
          销售属性
          <span>修改销售属性后，SKU列表自动刷新，请谨慎操作</span>
        </h3>
        <div v-for="(item, index) in info.attrList" :key="index">
          <el-form-item
            :prop="`attrList.${index}.values`"
            :rules="item.required ? validateBaseOrSeal : []"
            :label="item.title + '：'"
            v-if="item.kind === 1"
          >
            <el-tag
              v-for="(it, ind) in item.values"
              :key="ind"
              closable
              @close="tagClose(index, ind)"
            >
              {{ it }}
            </el-tag>
            <el-button type="primary" @click="addAttr(item, index)">
              添加属性
            </el-button>
          </el-form-item>
        </div>

        <h3>
          sku列表
          <span>商品上架后，对应的SKU方可在前端展示</span>
        </h3>
        <el-row class="row-center">
          <table v-if="tableDatath.length > 5">
            <tr>
              <th v-for="(item, index) in tableDatath" :key="index">{{ item }}</th>
            </tr>
            <tr v-for="(skuitem, skuindex) in Object.keys(skuData)" :key="skuindex">
              <template v-for="(vitem, vindex) in skuData[skuitem].values">
                <td :key="vindex">{{ vitem }}</td>
              </template>
              <td>
                <el-input
                  v-model="skuData[skuitem].price"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  placeholder="请输入价格"
                  @input="inputUpdate"
                ></el-input>
              </td>
              <td>
                <el-input
                  v-model="skuData[skuitem].stock"
                  :step="1"
                  :min="0"
                  placeholder="请输入库存"
                  @input="inputUpdate"
                ></el-input>
              </td>
              <td>
                <el-date-picker
                  v-model="skuData[skuitem].time"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @input="inputUpdate"
                ></el-date-picker>
              </td>
              <td>
                <el-input
                  v-model="skuData[skuitem].buyLimit"
                  :step="1"
                  :min="0"
                  placeholder="请输入限购数量"
                  @input="inputUpdate"
                ></el-input>
              </td>
              <td>
                <el-button
                  v-if="!skuData[skuitem].online"
                  type="primary"
                  @click="onOroffLine(skuData[skuitem], 1)"
                >
                  上架
                </el-button>
                <el-button v-else type="danger" @click="onOroffLine(skuData[skuitem], 0)">
                  下架
                </el-button>
              </td>
            </tr>
          </table>
        </el-row>
      </div>
    </el-form>
    <el-row class="row-center">
      <!-- 传为1的值就是全部保存并上架 -->
      <el-button type="primary" @click="saveBase(0)" :loading="saveAllLoading">
        全部保存
      </el-button>
      <el-button type="primary" @click="saveBase(1)" :loading="saveAllLoading">
        全部保存并上架
      </el-button>
    </el-row>
    <!-- 选取创作者 -->
    <el-dialog
      :visible="dialogVisible"
      title="选择用户"
      center
      width="60%"
      @close="dialogVisible = false"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <search-list ref="userList" :api-url="$url.UserList" :option="userUearchOpt" :itemPerRow="6">
        <el-table-column prop="uuid" label="uuid"></el-table-column>
        <el-table-column prop="showid" label="ID"></el-table-column>
        <el-table-column prop="nickname" label="昵称">
          <template slot-scope="scope">
            <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="" class="avatar" />
            <span>{{ scope.row.nickname }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="selectOne(scope.row)">选择这个</el-button>
          </template>
        </el-table-column>
      </search-list>
    </el-dialog>
    <!-- 添加属性 -->
    <el-dialog
      :visible="dialogVisibleAttr"
      title="添加属性值"
      width="60%"
      @close="dialogVisibleAttr = false"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <!-- multiple也支持但是不加 -->
      <el-select v-model="attValue" multiple v-if="attrbuteList.style === 'select'">
        <el-option
          v-for="it in attrbuteList.attrValues"
          :key="it.id"
          :label="it.attrValue"
          :value="it.attrValue"
        ></el-option>
      </el-select>
      <el-radio-group v-model="attValue" v-if="attrbuteList.style === 'radio'">
        <el-radio
          v-for="it in attrbuteList.attrValues"
          :key="it.id"
          :label="it.attrValue"
        ></el-radio>
      </el-radio-group>
      <el-checkbox-group v-model="attValueArr" v-if="attrbuteList.style === 'checkbox'">
        <el-checkbox
          v-for="it in attrbuteList.attrValues"
          :key="it.id"
          :label="it.attrValue"
        ></el-checkbox>
      </el-checkbox-group>
      <el-input v-model="attValue" v-if="attrbuteList.style === 'input'"></el-input>
      <el-date-picker
        v-if="attrbuteList.style === 'datetime'"
        v-model="attValueArrTime"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
      ></el-date-picker>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAttr = false">取 消</el-button>
        <el-button type="primary" @click="attrChoice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import EditMixins from 'mixins/Edit';
  import { FormRuleConf } from '@/config';
  import Editor from 'comp/Editor';
  import UploadResource from 'comp/UploadResource';
  export default {
    mixins: [EditMixins],
    components: {
      UploadResource,
      Editor,
    },
    data() {
      // 自定义验证
      let validatePass = (rule, value, callback) => {
        if (value[0]) {
          callback();
        } else {
          callback(new Error('该项为必填项'));
        }
      };
      return {
        // 属性必填项的验证
        validateBaseOrSeal: [
          { type: 'array', required: true, validator: validatePass, trigger: 'change' },
        ],
        // 选择发布用户dialog
        dialogVisible: false,
        // 选择属性的dialog
        dialogVisibleAttr: false,
        // 查询到的属性
        attrbuteList: {},
        // 添加属性值绑定的值
        attValue: '',
        // 添加属性值绑定的值（数组形式，多选框必须得是数组形式）
        attValueArr: [],
        // 添加属性值绑定的值（时间格式得特殊处理）
        attValueArrTime: [],
        // 到底是哪个要添加新属性
        attrIndex: '',
        // 分类数据
        categoryList: [],
        // 全部保存的loading
        saveAllLoading: false,
        // 表头
        tableDatath: ['售价(元)', '库存', '开售时间', '限购数量', '操作'],
        // sku表格数据
        skuData: [],
        // 新增返回的productId
        addHaveProductId: '',
        // 存储属性id
        attrIds: [],
        // 选择发布用户筛选
        userUearchOpt: [
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'nickname',
            label: '昵称',
          },
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'showid',
            label: 'ID',
          },
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'phone',
            label: '手机号码',
          },
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'uuid',
            label: 'uuid',
          },
        ],
        // 验证规则
        ...FormRuleConf.Mall,
      };
    },
    computed: {
      // 生成时间上次文件夹
      imgDate: function() {
        return this.dayjs().format('YYYY-MM-DD');
      },
    },
    created() {
      this.getCategory();
    },
    mounted() {},
    methods: {
      // 查询经纬度
      searchLongLat() {
        window.open('https://lbs.amap.com/tools/picker');
      },
      // 拖拽完得强制更新一下
      dragEnd() {
        this.$forceUpdate();
      },
      // 上下架
      onOroffLine(val, tag) {
        // 最好是这样写，但是没用
        // this.$set(val, 'online',tag)
        val.online = tag;
        this.$forceUpdate();
      },
      // 输入
      inputUpdate() {
        // 输入的时候强制更新
        this.$forceUpdate();
      },
      // 分类改变基础属性和销售属性都跟着改变
      categoryChange(val) {
        // 分类改变，sku列表为空,表头还原(这里也可以写空)
        this.skuData = [];
        this.tableDatath = [];

        this.$service.MallCategoryAttributeList({ categoryId: val }).then((res) => {
          let temp = res;
          let arr = [];
          if (temp.length > 0) {
            temp.forEach((i) => {
              i.attributeVos.forEach((j) => {
                arr.push(j);
              });
            });
          }
          // 分类，多加个values
          arr.forEach((item) => {
            item.values = [];
          });
          this.info.attrList = arr;

          // 强制更新
          this.$forceUpdate();
        });
      },
      // 得到分类数据
      getCategory() {
        this.$service.MallCategoryList({ page: 1, size: 100, enabled: 1 }).then((res) => {
          this.categoryList = res.rows;
        });
      },
      // tag关闭
      tagClose(index, ind) {
        // 到底是哪个要添加新属性
        this.attrIndex = index;
        this.info.attrList[this.attrIndex].values = this.info.attrList[
          this.attrIndex
        ].values.filter((item1, index1) => {
          return index1 != ind;
        });
        this.$forceUpdate();
        this.getTable();
      },
      // 选中属性
      attrChoice() {
        console.log(this.attValueArr);
        // 赋值还是照样用attValue好一些
        if (this.attValueArr.length > 0) {
          this.attValue = this.attValueArr;
        }
        if (this.attValueArrTime.length > 0) {
          let bb = this.attValueArrTime[0] + '-' + this.attValueArrTime[1];
          this.attValue = bb;
        }
        if (this.attValue && Array.isArray(this.attValue)) {
          this.info.attrList[this.attrIndex].values = this.info.attrList[
            this.attrIndex
          ].values.concat(this.attValue);
        } else if (this.attValue) {
          this.info.attrList[this.attrIndex].values.push(this.attValue);
        }
        // 选中属性的时候,得开始制作表格
        this.getTable();

        this.dialogVisibleAttr = false;
      },
      // 制作表格
      getTable() {
        let sku = [];
        // 先清空
        // this.skuData = [];
        this.tableDatath = ['售价(元)', '库存', '开售时间', '限购数量', '操作'];
        this.attrIds = [];
        // 临时保存表头
        let arr = [];
        this.info.attrList.forEach((item) => {
          // 只有是销售属性的时候在加入表格
          if (item.kind === 1 && item.values.length > 0) {
            // 制作表头,只有在有values的时候加入表头
            arr.push(item.title);
            // sku列表的值
            sku.push(item.values);
            // 这里就是加入所有的销售属性,下面匹配需要
            this.attrIds.push(item);
          }
        });
        // 处理表头
        this.tableDatath = arr.concat(this.tableDatath);

        // 得到整合后的数据
        sku = this.getCombination(sku);
        // 遍历整合后的数据,开始生成表格
        let equal = [];
        for (let k = 0; k < sku.length; k++) {
          // 这里是判断哪些值的保留
          let temp = sku[k].join('-');
          let arr = Object.keys(this.skuData);
          if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
              if (arr[i] === temp) {
                equal.push(arr[i]);
                break;
              }
            }
          }
        }
        // 一开始的时候清空
        Object.keys(this.skuData).forEach((a) => {
          if (!(equal.indexOf(a) > -1)) {
            delete this.skuData[a];
          }
        });

        sku.forEach((item) => {
          let shunxu = [];
          // 这里是把与values有关的属性id加进去,发请求的时候得拼接
          item.forEach((i) => {
            this.attrIds.forEach((j) => {
              if (j.values.indexOf(i) > -1) {
                shunxu.push(j.attrId);
              }
            });
          });
          // 这里就是如果没有就加进去，有的不动
          let rr = item.join('-');
          if (!(equal.indexOf(rr) > -1)) {
            this.skuData[rr] = {
              values: item,
              price: '',
              stock: 0,
              time: '',
              online: 0,
              buyLimit: '',
              ids: shunxu,
            };
          }
        });
      },
      // 添加属性
      addAttr(attr, index) {
        // 到底是哪个要添加新属性
        this.attrIndex = index;

        // 一开始的时候清空
        this.attValue = '';
        this.attValueArr = [];
        this.attValueArrTime = [];

        let id = attr.attrId;
        this.$service.MallAttrInfo({ id: id }).then((res) => {
          this.attrbuteList = res;
          this.dialogVisibleAttr = true;
        });
      },
      // 删除图片
      del(delImg) {
        this.info.imageList = this.info.imageList.filter((item, index) => {
          return index !== delImg;
        });
        this.$forceUpdate();
      },
      // 上传图片
      uploadImg(img) {
        if (!this.info.imageList) {
          this.info.imageList = [];
        }
        this.info.imageList.push(img.url);
        this.$forceUpdate();
      },
      // 选择发布用户
      selectOne(val) {
        this.info.nickname = val.nickname;
        this.info.uid = val.uuid;
        this.dialogVisible = false;
      },
      // 得到遍历后的数组,arr的格式的是[[]]的
      getCombination(arr) {
        let sarr = [[]];
        for (let i = 0; i < arr.length; i++) {
          let tarr = [];
          for (let j = 0; j < sarr.length; j++) {
            for (let k = 0; k < arr[i].length; k++) {
              tarr.push(sarr[j].concat(arr[i][k]));
            }
          }
          sarr = tarr;
        }
        return sarr;
      },
      // 保存基础属性
      saveBase(tag) {
        if (this.saveAllLoading) return;
        this.$refs.mallForm.validate((valid) => {
          if (valid) {
            this.saveAllLoading = true;
            // 处理数据
            this.info.cover = this.info.imageList[0];
            this.info.period = this.info.period
              ? this.info.period[0] + '~' + this.info.period[1]
              : '';
            // 改变模块，不要的值清空
            if (this.info.templateCode === '0') {
              this.info.skuImage = '';
              this.info.eticket = '';
              this.info.latitude = '';
              this.info.longitude = '';
              this.info.address = '';
              this.info.period = '';
            }

            // 请求
            this.$service.MallProductSave(this.info, JSON_HEADER).then((res) => {
              // 这里会返回productId下面的保存销售信息会需要
              this.addHaveProductId = res;

              this.saveSale(tag);
            });
          } else {
            this.$message.warning('还有未填写完整的信息哦');
          }
        });
      },
      // 保存销售属性
      saveSale(tag) {
        if (this.addHaveProductId || this.info.id) {
          // 数据处理
          // 属性列表数据处理
          this.info.attrList.forEach((item) => {
            // 如果是时间就是数组里面加数组
            if (item.style === 'datetime') {
              if (item.values[0] && item.values[0].length > 0) {
                item.values = [item.values[0][0] + '~' + item.values[0][1]];
              } else {
                item.values = [];
              }
            }
          });
          // 如果没有选属性值，就不上传了
          this.info.attrList = this.info.attrList.filter(
            (item) => item.values.length > 0 && item.values[0],
          );

          // 这里是处理数据，变成数组
          let _ = [];
          Object.keys(this.skuData).forEach((i) => {
            _.push(this.skuData[i]);
          });
          this.skuData = _;

          // sku列表数据处理
          this.skuData.forEach((item) => {
            if (item.time) {
              item.startedAt = item.time[0];
              item.endedAt = item.time[1];
            }
            // 如果是全部保存并上架，就改变一下onLine
            if (tag) {
              item.online = 1;
            }

            //拼接属性id和values
            let temp = [];
            item.ids.forEach((k, l) => {
              temp = temp.concat(k, item.values[l]);
            });
            item.skuPath = temp.join('^V^');

            item.productId = this.info.id || this.addHaveProductId;
          });
          // 请求
          this.$service
            .MallProductSaveSaleInfo(
              {
                attrList: this.info.attrList,
                skuList: this.skuData,
                productId: this.info.id || this.addHaveProductId || '',
              },
              JSON_HEADER,
            )
            .then((res) => {
              this.saveAllLoading = false;
              this.$message.success('保存成功');
              this.$tabs.open({
                name: 'MallGoodsDetail',
                params: { id: this.addHaveProductId },
              });
              this.addHaveProductId = '';
            });
        } else {
          this.$message.warning('请先保存商品基本信息');
        }
      },
      // 得到数据
      getInfo() {
        if (!this.id || this.$route.name != 'MallGoodsDetail' || this.infoGetting) return;
        this.infoGetting = true;
        this.$service
          .MallProductInfo({ id: this.$route.params.id })
          .then((res) => {
            this.info = { ...res };

            // 如果是编辑就赋值sku列表
            this.skuData = this.info.skuList;
            // 处理数据
            // 时间格式处理
            this.info.period = this.info.period ? this.info.period.split('~') : '';
            // 属性里的值如果是时间就是数组里面加数组
            this.info.attrList.forEach((item) => {
              if (item.style === 'datetime') {
                item.values = [item.values[0].split('~')];
              }
            });
            // 处理sku列表的数据
            let obj = {};
            this.skuData.forEach((item) => {
              let r = [];
              item.values = [];
              item.ids = [];
              r = item.skuPath.split('^V^');
              // 解开属性id和values的拼接
              r.forEach((ite, inde) => {
                if (inde % 2) {
                  item.values.push(ite);
                } else {
                  item.ids.push(ite);
                }
              });
              item.time = item.endedAt ? [item.startedAt, item.endedAt] : '';

              obj[item.values.join('-')] = item;
            });
            // skuData现在得是对象的格式
            this.skuData = obj;
            // 得把表头变为原来的在加进去
            this.tableDatath = ['售价(元)', '库存', '开售时间', '限购数量', '操作'];
            let arr = [];
            this.info.attrList.forEach((item) => {
              // 销售属性的才加进去
              if (item.kind) {
                arr.push(item.title);
              }
            });
            this.tableDatath = arr.concat(this.tableDatath);
          })
          .finally(() => {
            this.infoGetting = false;
          });
      },
    },
  };
</script>
<style lang="less" scoped>
  /deep/ .el-dialog {
    .avatar {
      width: 50px;
      height: 50px;
      vertical-align: middle;
      display: inline-block;
    }
  }
  .goods-detail {
    // 修改element的样式
    /deep/ .el-select,
    /deep/ .sc-select,
    /deep/ .el-input-number {
      width: 390px;
    }
    /deep/ .el-tag {
      margin-right: 10px;
    }

    // 自己的样式
    h2 {
      padding-left: 20px;
      border-left: 5px solid #1d6be0;
      line-height: 1;
      margin-bottom: 10px;
      margin-top: 10px;
    }

    h3 {
      margin-bottom: 10px;
      span {
        margin-left: 20px;
        font-size: 12px;
        color: #e6a23c;
      }
    }

    .box {
      padding: 30px;
      background-color: #ededed;
      border-radius: 10px;
    }

    .goods-img {
      display: inline-block;
      width: 150px;
      height: 150px;
      margin-top: 10px;
      margin-right: 20px;
    }

    .row-center {
      text-align: center;
      /deep/ .el-button {
        margin-top: 20px;
      }
    }

    // 图片
    .img-oper {
      position: relative;
      display: inline-block;
      width: 150px;
      height: 150px;
      line-height: 150px;
      margin-right: 10px;
      img {
        width: 150px;
        height: 150px;
        display: block;
      }
      .oper {
        position: absolute;
        width: 100%;
        height: 20px;
        top: 90px;
        left: 0;
        transition: all 0.3s ease;
        text-align: center;
        color: #000;
        box-sizing: border-box;
        opacity: 1;
        cursor: pointer;
        z-index: 10;
        font-size: 20px;
        i {
          margin: 0px 10px;
        }
      }
    }

    .gap {
      margin-top: 40px;
    }

    th {
      background-color: #ccc;
    }

    table {
      text-align: center;
      border-collapse: collapse;
      td,
      th {
        border: 1px solid #000;
        padding: 10px;
        /deep/ .el-button {
          margin-top: 0px !important;
        }
      }
    }

    // 商品图片的验证错误解释
    .img-list {
      /deep/ .el-form-item__content .el-form-item__error {
        padding-top: 25px;
      }
    }
  }
</style>
